package org.quipu.client;

import org.quipu.client.events.AppEventBus;
import org.quipu.client.events.CurrenciesOutOfDateEvent;
import org.quipu.dto.CurrencyDto;

public class CurrencyListBox extends AppListBox {

    public CurrencyListBox(AppEventBus eventBus, AppCache cache, Long selectedCurrencyId) {
        super(eventBus, cache, CurrenciesOutOfDateEvent.class, null, selectedCurrencyId);
        getListBox().addStyleName("currenciesList");
        refresh();
    }

    @Override
    protected final void refresh() {
        getListBox().clear();
        int selectedIndex = -1;
        int i = 1;
        getListBox().addItem("", "0");
        for(CurrencyDto currency : getCache().getCurrencies()) {
            getListBox().addItem(currency.getTitle(), String.valueOf(currency.getId()));
            if(currency.getId().equals(getSelectedId())) {
                selectedIndex = i;
            }
            i++;
        }
        if(selectedIndex < 0) {
            setSelectedId(null);
        } else {
            getListBox().setSelectedIndex(selectedIndex);
        }
    }
}
